<template>
    <div class="common-layout">
        <el-container>
            <el-aside width="200px">
                <el-affix :offset="10">
                    <el-radio-group v-model="isCollapse" style="margin-bottom: 20px">
                        <el-radio-button :value="false">展开</el-radio-button>
                        <el-radio-button :value="true">折叠</el-radio-button>
                    </el-radio-group>
                    <el-menu default-active="1" class="el-menu-vertical-demo" :collapse="isCollapse" @open="handleOpen"
                        @close="handleClose" @select="handleSelect">
                        <el-menu-item index="/index">
                            <el-icon>
                                <House />
                            </el-icon>
                            <template #title>首页 </template>
                        </el-menu-item>
                        <el-menu-item index="/booklist">
                            <el-icon>
                                <Folder />
                            </el-icon>
                            <template #title>图书列表</template>
                        </el-menu-item>
                        <el-menu-item index="/booksales">
                            <el-icon>
                                <Reading />
                            </el-icon>
                            <template #title>图书售卖</template>
                        </el-menu-item>
                        <el-menu-item index="/help">
                            <el-icon>
                                <Warning />
                            </el-icon>
                            <template #title>帮助</template>
                        </el-menu-item>
                    </el-menu>
                    <!-- 路由出口，用于显示当前路由对应的组件 -->
                    <router-view></router-view>
                </el-affix>
            </el-aside>
            <el-container>
                <el-affix :offset="0">
                    <el-header style="
              display: flex;
              align-items: center;
              height: 60px;
              border: 1px solid #f5f6fe;
            ">
                        <!-- 添加 flex-grow: 1 使该 div 占据剩余空间 -->
                        <div style="flex-grow: 1"></div>

                        <router-link to="/cart" style="
                display: flex;
                align-items: center;
                justify-content: center;
                height: 50px;
                padding-right: 20px;
                text-decoration: none; /* 去除默认下划线 */
                color: inherit; /* 继承父元素颜色 */
              ">
                            <el-badge :value="bookStore.orderedBooksCount" :max="10" class="badge-item">
                                <span class="icon-wrapper">
                                    <el-icon style="font-size: 25px">
                                        <ShoppingCart />
                                    </el-icon>
                                </span>
                            </el-badge>
                        </router-link>

                        <div style="
                display: flex;
                align-items: center;
                justify-content: center;
                height: 50px;
                padding-right: 20px;
              ">
                            <span class="icon-wrapper">
                                <el-icon style="font-size: 25px">
                                    <Setting />
                                </el-icon>
                            </span>
                        </div>

                        <div style="padding-right: 20px">
                            <el-popover placement="bottom" trigger="hover">
                                <el-menu mode="vertical">
                                    <el-menu-item index="1" @click="handleMenuItemClick(1)">个人中心</el-menu-item>
                                    <el-menu-item index="2" @click="handleMenuItemClick(2)">关于我们</el-menu-item>
                                    <el-menu-item index="3" @click="handleMenuItemClick_exit(3)">退出登录</el-menu-item>
                                </el-menu>

                                <template #reference>
                                    <el-avatar
                                        src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
                                </template>
                            </el-popover>
                        </div>
                    </el-header>
                </el-affix>
                <el-main>
                    <h3 style="text-align: left">购物车</h3>

                    <el-table ref="multipleTableRef" :data="bookStore.orderedBooks" row-key="title" style="width: 100%"
                        @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="55" />
                        <el-table-column label="商品信息" min-width="120">
                            <!-- 自定义列模板 -->
                            <template #default="{ row }">
                                <div class="product-info">
                                    <img :src="row.img" alt="商品图片" class="product-image" />
                                    <div class="product-details">
                                        <p class="product-title">{{ row.title }}</p>
                                        <p class="product-author">{{ row.author }}</p>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column property="price" label="单价" min-width="80" />
                        <el-table-column label="数量" min-width="120">
                            <template #default="{ row }">
                                <el-input-number v-model="row.quantity" :min="1" @change="handleQuantityChange(row)"
                                    style="width: 120px"></el-input-number>
                            </template>
                        </el-table-column>
                        <el-table-column label="金额" min-width="80">
                            <template #default="{ row }">
                                {{ (row.price * row.quantity).toFixed(1) }}
                            </template>
                        </el-table-column>
                        <el-table-column fixed="right" label="操作" min-width="80">
                            <template #default="scope">
                                <el-button link type="primary" size="small" @click.prevent="deleteRow(scope.$index)">
                                    Remove
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="total-and-button">
                        <p class="total-price">
                            总价: {{ totalPrice.toFixed(1) }}
                        </p>
                        <el-button class="settle-button">结算</el-button>
                    </div>

                </el-main>
                <el-footer style="
            display: flex;
            justify-content: center;
            align-items: center;
            height: 60px;
          ">
                    <div>Designed with by XXX</div>
                </el-footer>
            </el-container>
        </el-container>
    </div>
</template>

<script lang="ts" setup>
import { reactive } from "vue";
import { ref, computed } from "vue";
import {
    Reading,
    House,
    Warning,
    Folder,
    Search,
    ArrowRight,
    CaretBottom,
    CaretTop,
    Top,
    Bottom,
    Close,
    Setting,
    ShoppingCart,
} from "@element-plus/icons-vue";
import type { TabsPaneContext, TableInstance } from "element-plus";
import { onMounted } from "vue";
import { useRouter } from "vue-router";
import {
    ElPopover,
    ElAvatar,
    ElMenu,
    ElMenuItem,
    ElMessage,
    ElMessageBox,
} from "element-plus";

import "../mock/iconfont.js";
import { useLogout } from "../composables/useLogout";
import { useBookStore } from '../stores/bookStore';

const router = useRouter();
const bookStore = useBookStore();

// 定义书籍对象的类型
interface Book {
    id: number;
    title: string;
    img: string;
    price: number;
    author: string;
    quantity: number;
    isDetailsVisible: boolean;
};

const multipleTableRef = ref<TableInstance>()
// const multipleSelection = ref<Book[]>([])

const selectedRows = ref<Book[]>([]);

// 定义 imageItem 类型
interface ImageItem {
    src: string;
    alt: string;
    bgColor: string;
}

const isCollapse = ref(false);

// 创建一个响应式的布尔变量，初始值设为true，表示div初始是可见的
const isDivVisible = ref(true);

const handleOpen = (key: string, keyPath: string[]) => {
    console.log(key, keyPath);
};
const handleClose = (key: string, keyPath: string[]) => {
    console.log(key, keyPath);
};

const handleSelect = (key: string) => {
    // 根据菜单项的 index 值切换页面

    router.push(key);
};

const searchText = ref("");

const handleMenuItemClick = (index: number) => {
    console.log(`你点击了选项 ${index}`);
};

const { isLoading, logout } = useLogout();
const handleMenuItemClick_exit = async (index: number) => {
    console.log(`你点击了选项 ${index}`);
    await logout();
};

onMounted(() => {
    const userData = localStorage.getItem("userData");
    if (!userData) {
        // 如果没有获取到数据，跳转到登录页
        router.push("/login");
    }
});

const handleSelectionChange = (val: Book[]) => {
    // multipleSelection.value = val
    selectedRows.value = val;
}

const deleteRow = (index: number) => {
    bookStore.orderedBooks.splice(index, 1)
}

const handleQuantityChange = (row: Book) => {
    // 更新 Pinia 存储中的数据
    const index = bookStore.orderedBooks.findIndex(item => item.title === row.title);
    if (index !== -1) {
        bookStore.orderedBooks[index].quantity = row.quantity;
    }
    console.log('数量已更新:', row);
};

const totalPrice = computed(() => {
    return selectedRows.value.reduce((total, item) => {
        return total + item.price * item.quantity;
    }, 0);
});

</script>

<style scoped>
.el-header {
    /* background-color: gray; */
    background-color: #fff;
}

.el-aside {
    background-color: #fff;
    /* background-color: pink; */
    border: 1px solid #f5f6fe;
}

.el-main {
    background-color: #f5f6fe;
    /* background-color: orange; */
}

.el-menu {
    border-right: none;
}

.el-menu-vertical-demo:not(.el-menu--collapse) {
    width: 200px;
    min-height: 400px;
}

.input-with-select .el-input-group__prepend {
    background-color: var(--el-fill-color-blank);
}

.close-icon {
    position: absolute;
    top: 10px;
    right: 10px;
    cursor: pointer;
    font-size: 16px;
}

.el-row {
    margin-bottom: 20px;
}

.el-row:last-child {
    margin-bottom: 0;
}

.el-col {
    border-radius: 4px;
}

.grid-content {
    border-radius: 4px;
    min-height: 36px;
}

:global(h2#card-usage ~ .example .example-showcase) {
    background-color: var(--el-fill-color) !important;
}

p {
    margin: 0;
    padding: 0;
    font-size: 14px;
    text-align: left;
}

.p-vertically-center {
    display: flex;
    /* 使用 Flexbox 布局 */
    flex-direction: column;
    /* 垂直排列子元素 */
    justify-content: center;
    /* 垂直居中 */
    align-items: center;
    /* 水平居中 */
    height: 100%;
    /* 确保容器有高度 */
}

.p-vertically-center p {
    margin: 5px 40px;
    /* 为每个段落添加上下外边距 */
}

/* Vue 3 中使用 ::v-deep 穿透样式，将所有标签页标题文字加粗 */
::v-deep .el-tabs__item {
    font-weight: bold;
}

/* 确保弹出框有最小宽度 */
.el-popover {
    min-width: 120px;
    z-index: 1000;
    /* 确保弹出框显示在最上层 */
}

.booklistdiv {
    position: relative;
    margin: 20px;
    margin-bottom: 20px;
    background-color: #fff;
}

.booklistdiv::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(128, 128, 128, 0.5);
    z-index: 1;
    /* 确保覆盖层在图片之上 */
}

.booklistdiv p {
    margin: 0 0 5px 10px;
}

.book-image {
    width: 100%;
    height: 200px;
    object-fit: contain;
    display: block;
}

.booktitle {
    position: absolute;
    /* 设置为绝对定位 */
    bottom: 0;
    /* 让 booktitle 的底部与 booklistdiv 的底部重合 */
    left: 0;
    /* 左对齐 */
    width: 100%;
    /* 宽度占满父元素 */
    background-color: rgba(255, 255, 255, 1);
    /* 半透明背景 */
    color: black;
    /* 文字颜色 */
    padding: 5px;
    /* 内边距 */
    box-sizing: border-box;
    /* 包含内边距和边框在宽度内 */
    z-index: 2;
    /* 确保标题在覆盖层之上 */
    text-align: left;
    /* 让文字左对齐 */
}

.booktitle h4 {
    margin: 10px 0 10px 10px;
}

.icon {
    width: 1em;
    height: 1em;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
}

.overflow-menu-icon {
    float: right;
    cursor: pointer;
    font-size: 20px;
}

.message-box-content {
    white-space: pre-line;
}

.badge-item {
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

.icon-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
}

.product-info {
    display: flex;
    align-items: center;
    padding: 8px;
}

.product-image {
    max-width: 80px;
    max-height: 80px;
    border-radius: 4px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    margin-right: 16px;
}

.product-details {
    display: flex;
    flex-direction: column;
}

.product-title {
    font-size: 14px;
    font-weight: 500;
    margin-bottom: 4px;
}

.product-author {
    font-size: 12px;
    color: #606266;
}

.total-and-button {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    /* 设置总价和按钮之间的间隙 */
    margin-top: 10px;
    margin-right: 10px;
    align-items: center;
}

.total-price {
    text-align: right;
    font-size: 18px;
    font-weight: bold;
    color: #333;
    /* margin-top: 10px;
    margin-right: 10px; */
}

.settle-button {
    background-color: #409eff;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 8px 18px;
    cursor: pointer;
    transition: background-color 0.3s ease;
    font-size: 18px;
    display: inline-flex;
    justify-content: center;
    align-items: center;
    letter-spacing: 10px;
}
</style>